package MyThread;

import java.util.PriorityQueue;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2023-01-04
 * Time: 17:33
 */
// 自己实现一个定时器
class MyTask implements Comparable<MyTask> {
    private Runnable runnable;
    private long time;

    public MyTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = time;
    }

    // 返回任务时间
    public long getTime() {
        return this.time;
    }

    // 执行任务
    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    // 扫描线程
    private Thread t = null;
    // 用一个带有优先级的阻塞队列来保存任务
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    public MyTimer() {
        t = new Thread(() -> {
            // 1. 先取出任务, 查看任务时间
            // 2. 如果任务时间未到, 把任务塞回队列
            // 3. 时间到了, 执行任务

            while (true) {
                try {
                    synchronized (this) {
                        MyTask myTask = queue.take();
                        long curTime = System.currentTimeMillis();
                        if (myTask.getTime() > curTime) {
                            // 时间未到, 塞回去
                            queue.put(myTask);
                            this.wait(myTask.getTime() - curTime);

                        } else {
                            // 时间到了, 执行任务
                            myTask.run();
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.start();
    }

    public void schedule (Runnable runnable, long time) {
        MyTask myTask = new MyTask(runnable, time + System.currentTimeMillis());
        queue.put(myTask);

        synchronized (this) {
            this.notify();
        }
    }
}

public class ThreadDemo25 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行任务1");
            }
        }, 3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行任务2");
            }
        }, 2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行任务3");
            }
        }, 1000);
    }
}
